/**
 * 各角色授权功能模块业务处理
 */
import {
  api,
  util,
  storage
} from '../util'
import {
  router
} from '../router'
import {
  GoodsNumCache
} from '../modules/propertycache'
import {FIleOpera} from "../common/file-opera"
// 登录SessionKey
const login_cookie_key = "LoginSessionKey"
const login_cookie_role_key ="LoginSessionRoleKey"
const login_cookie_token_key = "LoginSessionTokenKey"
const login_cookie_expiretime_key = "LoginSessionExpireTimeKey"
const login_cookie_virtualdir_key = "LoginSessionVirtualDirKey"
//授权全局变量
const Authorize={
  entity:null,
  expiretime: 0,
  flag:"store"
}
class BaseRole{
  // 构造函数
  constructor(data, flag) {
    this.proprietorId = data.role.ProprietorId;
    this.proprietor = data.role.Proprietor;
    this.fkId = data.role.Id;
    this.flag = flag;
    this.virtualdir = data.virtualDir;
    this.manager = data.manager;
    this.role = data.role;
    this.expiretime = data.expiretime || 0;
    Authorize.entity = this;
    Authorize.flag = flag;
    Authorize.expiretime = this.expiretime;
  }
  // 设置Cookie值
  setCookie() {
    storage.put(login_cookie_key, this, 0);
    storage.put(login_cookie_role_key, this.flag, 0);
    storage.put(login_cookie_expiretime_key, this.expiretime, 0);
    storage.put(login_cookie_token_key, this.manager.Token, 0);
    storage.put(login_cookie_virtualdir_key, this.virtualdir, 0);

    FIleOpera.save(JSON.stringify(Authorize),(res)=>{
      console.log(JSON.stringify(res));
    });
  }

  // 获取实体
  static getEntity() {
    //优先取全局变量里面
    var entity = Authorize.entity;
    //失效时取缓存中
    if (entity == null || entity == undefined || entity.role == null) {
      entity = storage.get(login_cookie_key);
    }
    if (entity != null && entity != undefined && entity.role != null) {
      return entity;
    }
    return null;
  }

  // 判断是否登录
  static isLogin(flag,callback) {
    //优先取全局变量里面
    var entity = Authorize.entity;
    var expiretime = Authorize.expiretime;
    //全局变量是否失效
    var isOver = false;
    //失效时取缓存中
    if (entity == null || entity == undefined || entity.role == null||entity.manager==null||Object.keys(entity.role).length==0) {
      entity = storage.get(login_cookie_key);
      expiretime = storage.get(login_cookie_expiretime_key);
      isOver = true;

    }
    //读取文件中的
    if (entity == null || entity == undefined || entity.role == null||entity.manager==null||Object.keys(entity.role).length==0) {
      FIleOpera.read((res)=>{
         if(res.success){
          entity =res.data.entity;
          expiretime = res.data.expiretime;
          isOver = true;
         }
      });
    }
    //角色不上同时直接返加
    else if (entity.flag != flag){
      return -1;
    }
    if (entity != null && entity != undefined && entity.role != null&&entity.manager!=null&&
      entity.fkId>0) {
      //如果失效，则重写赋值
      if (isOver) {
        callback({ role: entity.role, manager: entity.manager, expiretime: expiretime, token: entity.manager.Token, virtualDir: entity.virtualdir,flag:entity.flag });
      }
      //判断过期时间
      if (expiretime != null && expiretime != undefined && expiretime != "") {
        if (new Date().getTime() < expiretime) {
          return 1;
        }
      }
      else if (expiretime == 0) {
        return 1;
      }
    }
    return 0;
  }

}
/**
 * 各个角色登录授权信息
 */
class Store extends BaseRole {
  fkFlag = 1;
  // 页面跳转
  static redirect(returnUrl, s) {
    var url = "login";
    var params = {
      path: url,
      params: {
        role: "store",
        returnUrl: returnUrl
      }
    };
    if (s == undefined || s == 1) {
      router.redirect(params);
    } else if (s == 2) {
      router.switchTab(params);
    } else if (s == 3) {
      router.navigate(params);
    }
  }
}
/**
 * 各个角色登录授权信息
 */
class Supplier extends BaseRole {
  fkFlag = 2;
  // 页面跳转
  static redirect(returnUrl, s) {
    var url = "login";
    var params = {
      path: url,
      params: {
        role: "supplier",
        returnUrl: returnUrl
      }
    };
    if (s == undefined || s == 1) {
      router.navigate(params);
    } else if (s == 2) {
      router.switchTab(params);
    } else if (s == 3) {
      router.navigate(params);
    }
  }
}
class Clerk extends BaseRole {
  fkFlag = 2;
  // 页面跳转
  static redirect(returnUrl, s) {
    var url = "login";
    var params = {
      path: url,
      params: {
        role: "clerk",
        returnUrl: returnUrl
      }
    };
    if (s == undefined || s == 1) {
      router.navigate(params);
    } else if (s == 2) {
      router.switchTab(params);
    } else if (s == 3) {
      router.navigate(params);
    }
  }
}
/**
 * 对外提供对象支持
 */
module.exports = {
  loginRole:function(){
    let role=storage.get(login_cookie_role_key)||"store";
    return role;
  },
  //判断是否登录
  isLogin: function(role) {
    let status= BaseRole.isLogin(role, (data)=>{
      this.setCookie(data.flag,data);
    });
    // if(status==-1){
    //   this.loginOut();
    // }
    return status==1;
  },
  /**
   * 页面跳转
   * @param: 角色
   * @param: 跳转页面
   * @param: 跳转类型,1-普通跳转,2-带底部页面跳转,3-navigate
   */
  redirect: function(role, returnUrl, s) {
    if (role == "store") {
      util.setBeforeLoginData()
      Store.redirect(returnUrl, s);
    }
  },
  /*
  *获取缓存中实体
  */
  getEntity: function(role='store') {
    if(this.isLogin(role)){
      let entity= BaseRole.getEntity();
      if (entity.flag!=role) {
        return null;
      }
      return entity;
    }
    return null;
  },
  /**
   * 获得默认值
   */
  getDefault:function(){
    return {
      fkId:0,
      fkFlag:2,
      manager:{
        Token:""
      },
      role:{
        LevelId:0
      }
    }
  },
  /**
   * 设置cookie
   */
  setCookie: function(role, data) {
    if (role == "store") {
      new Store(data, role).setCookie();
    }
    else if (role == "supplier") {
      new Supplier(data, role).setCookie();
    }
    else if (role == "vendor") {
      new Supplier(data, role).setCookie();
    }
    else if (role == "clerk") {
      let c_data=data;
      if(data.role==undefined){
      c_data={
        role:{
          Id:data.Id,
          Proprietor:data.Proprietor,
          Name:data.Name,
          ProprietorId:data.ProprietorId
        },
        manager:{
          Id:data.Id,
          Name:data.Name,
          Token:data.Token,
          UserName:data.UserName,

        },
        expiretime:data.expiretime,
        virtualDir:data.virtualDir
      }
    }
      new Clerk(c_data, role).setCookie();
    }
  },
  /**
   * 退出登录
   */
  loginOut:function(){
    Authorize.flag = "store";
    Authorize.expiretime = 0;
    Authorize.entity = null;
    FIleOpera.del((res)=>{
      console.log(JSON.stringify(res));
    });
    wx.removeStorageSync(login_cookie_key);
    wx.removeStorageSync(login_cookie_token_key);
    wx.removeStorageSync(login_cookie_expiretime_key);
    wx.removeStorageSync(login_cookie_role_key);
    util.removeCategoryCache()
    GoodsNumCache.clearGoodsNumCache();
  }
}